<?php
namespace API\Controller;
use Think\Controller;
class AuthController extends CommonController {
	
	public function sdk(){
                        	 //1.获取code
                         	$code = I('get.code');
                         	$key = C('key');
                         	$secret =C('secret');
                         	$redirect_uri=C('redirect_uri');
                         	//2.获取access token
                         	$o = new \Org\Weibo\SaeTOAuthV2($key,$secret);
                         	$keys = array();
                         	$keys['code'] = $code;
                         	$keys['redirect_uri'] = $redirect_uri;
                         	$token = $o->getAccessToken( 'code', $keys );
                        	 //3.获取用户信息

                         	$c = new \Org\Weibo\SaeTClientV2($key , $secret , $token['access_token'] );
                         	$uid_get = $c->get_uid();
                         	$uid = $uid_get['uid'];
                         	$userInfo = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息

                         	//4.用户登录或注册
                         	$User = M('User');
                         	$res = $User->where("openid ={$userInfo['id']} ")->find();

                         	if ($res == false) {
                          	  //注册，插入用户信息
	                                 $data = array(
	                                                'openid'=>$userInfo['id'],
	                                                'username'=>$userInfo['name'],
	                                                'headimg'=>$userInfo['avatar_large'],
	                                                'addtime'=>time()
	                                 );
                                      	$rel=$User->add($data);
	                                if (!$rel) {
	                                                $this->error("注册失败");
	                                }else{
	                                                $_SESSION['USERID']  = $rel;
	                                                $_SESSION['USERHEADIMG'] = $userInfo['avatar_large'];
	                                                $_SESSION['USERNAME'] = $userInfo['name'];
	                                }
                                      
	                }else{
	                                 $_SESSION['USERID'] = $res['id'];
	                                 $_SESSION['USERHEADIMG'] = $res['headimg'];
	                                 $_SESSION['USERNAME'] = $res['username'];
	                 }

                         	$this->redirect("/Home/Person/index");

            	}

}